package com.pg.agent.engine.service.service.impl;



public class SopInitServiceImpltb {

/*

    @Value("${spring.profiles.active}")
    private String profile;
    private static final int expiredTime = 60 * 60 * 60;


    public SessionObject init(AgentExeDTO AgentExeDTO) {
        SessionObject SessionObject = new SessionObject();
        AISOP aisop = getAiSOP(AgentExeDTO.getSopVersionId());
        AIEnvironment aiEnvironment = initEvnironment(aisop);

        SessionObject.setAiEnvironment(aiEnvironment);
        SessionObject.setAiSOP(aisop);
        return SessionObject;
    }

    public AIEnvironment initEvnironment(AISOP aisop) {
        AIEnvironment aiEnvironment = new AIEnvironment();
        ShareMemory shareMemory = new ShareMemory();
        shareMemory.setLongMemory(new ArrayList<>());
        shareMemory.setShortMemory("");

        aiEnvironment.setShareMemory(shareMemory);
        Map<String, AIAgent> evnAgentMap = new HashMap<>();
        Map<String, String> summarySystemPrompt = new HashMap<>();
        Map<String, String> summaryLastPrompt = new HashMap<>();
        Map<String, String> environmentPrompt = new HashMap<>();
        for (Map.Entry<String, AIState> aiState : aisop.getStates().entrySet()) {
            AIState value = aiState.getValue();
            summarySystemPrompt.put(value.getName(), PromptConstant.DEFAULT_ENVIRONMENT_SUMMARY_SYSTEM_PROMPT);
            summaryLastPrompt.put(value.getName(), PromptConstant.DEFAULT_ENVIRONMENT_SUMMARY_LAST_PROMPT);
            environmentPrompt.put(value.getName(), value.getEnvironmentPrompt());
            for (AIAgent aiAgent : value.getAiAgentList()) {
                evnAgentMap.put(aiAgent.getName(), aiAgent);
            }
        }
        //environment.setAgents(evnAgentMap);
        aiEnvironment.setEnvironmentPrompt(environmentPrompt);
        aiEnvironment.setSummarySystemPrompt(summarySystemPrompt);
        //aiEnvironment.setSummaryLastPrompt(summaryLastPrompt);
        Config config = new Config();
        config.setApiKey("c6fd6677ad6549b1ba87cefb02785101");
        config.setApiBase("https://test-openai-419.openai.azure.com/");
        config.setOpenaiApiType("");
        config.setTopK("3");
        config.setProxy("");
        config.setMaxChatHistory(10);
        aiEnvironment.setConfig(config);
        return aiEnvironment;
    }


    private AISOP getAiSOP(Long versionId){
        AISOP aisop = null;
        aisop =  initAiSop();
        aisop.setDescription(Agent.getDescription());
        return aisop;
    }
    private AgentNode getAgentNode(String agentNodeId, Map<String, List<String>> relMap, Map<String, AgentNode> agentNodeMap, Map<String, ComponentNode> componentNodeMap) {
        AgentNode agentNode = agentNodeMap.get(agentNodeId);
        return agentNode;
    }

    public AISOP initAiSop() {
        // 初始化SOP
        AISOP aisop = new AISOP();
        aisop.setId(Agent.getAgentId());
        aisop.setName(Agent.getAgentName());
        aisop.setRunMode(version.getSopType());
        aisop.setSummaryHistory(Integer.valueOf(1).equals(startNode.getSummaryHistoryQa()) ? true : false);
        aisop.setBeginQuery(startNode.getBeginQuery());
        List<AgentInParamSetDTO> inParamList = startNode.getInParamList();
        if (CollectionUtil.isNotEmpty(inParamList)) {
            //判断是否必填
            for (AgentInParamSetDTO AgentInParamSetDTO : inParamList) {
                ClifeAssert.bizError(ObjectUtil.isEmpty(AgentInParamSetDTO.getParamCode()), ErrorCodeEnum.LACK_PARAM_CODE);
                ClifeAssert.bizError(ObjectUtil.isEmpty(AgentInParamSetDTO.getParamName()), ErrorCodeEnum.LACK_PARAM_NAME);
                ClifeAssert.bizError(ObjectUtil.isEmpty(AgentInParamSetDTO.getRequired()), ErrorCodeEnum.LACK_PARAM_REQUIRE);
                ClifeAssert.bizError(ObjectUtil.isEmpty(AgentInParamSetDTO.getParamType()), ErrorCodeEnum.LACK_PARAM_TYPE);
            }
        }
        // 增加快捷输入标签。
        if (ObjectUtil.isNotEmpty(startNode.getDesc()) && startNode.getDesc().indexOf("#") > 0) {
            String[] split = startNode.getDesc().split("#");
            aisop.setLabelList(Arrays.asList(split));
        }

        //sop默认大模型
        if (startNode.getComponentId() != null) {
            aisop.setComLLM(getLLMComponent(startNode.getComponentId()));
        } else {
            //默认ChatGPT-3.5 todo,暂时写死
            aisop.setComLLM(getLLMComponent(138l));
        }
        //sop关联状态
        Map<String, AIState> aiStateMap = new HashMap<>();
        List<AIState> aIStateList = new ArrayList<>();

        if (ObjectUtil.isEmpty(startNode.getStateNodes())) {
            throw new BizException(ErrorCodeEnum.MICRO_APP_SENSE_NODE);
        }
        //初始化状态
        List<StateNode> stateNodes = startNode.getStateNodes();
        Map<String, String> allState = stateNodes.stream().collect(Collectors.toMap(StateNode::getNodeId, StateNode::getStateName,(key1 , key2)-> key1));
        if (judgeSameName(allState)){
            throw new BizException(STATUS_NOT_SAME_NAME);
        }
        //状态的意图切换
        IntentRecognition stateConvert = new IntentRecognition();
        settingSwitchData(startNode.getStateSwitchNode(), stateConvert, allState);

        aisop.setIntentRecognition(stateConvert);
        for (StateNode stateNode : stateNodes) {
            //初始化状态
            AIState aiState = initStateNodeData(aisop, stateNode);
//            aisop.setRoot(stateNode.getStateName());
//            aisop.setCurrentState(aiState);
            aiStateMap.put(aiState.getName(), aiState);
            aIStateList.add(aiState);
        }
        aisop.setStateList(aIStateList);
        aisop.setStates(aiStateMap);

        return aisop;
    }

    *//**
     * 同一个意图识别下，不能存在相同名字的场景或agent
     * @param allState
     * @return
     *//*
    private Boolean judgeSameName(Map<String, String> allState){
        Boolean flag = false;
        if (CollectionUtil.isNotEmpty(allState)){
            Collection<String> name = allState.values();
            Set<String> stringSet = new HashSet<>(name);
            if (name.size()>stringSet.size()){
                flag = true;
            }
        }
        return flag;
    }

    private List<KeyWordRelName> initKeyWordRelStateList(Map<String, String> all, List<BigModelSwitch> bigModelSwitchList) {
        log.info("keyword--initKeyWordRelStateList:{}",JSONObject.toJSONString(bigModelSwitchList));
        if (CollectionUtil.isNotEmpty(bigModelSwitchList)) {
            List<KeyWordRelName> keyWordRelStateList = bigModelSwitchList.stream().map(e -> {
                KeyWordRelName keyWordRelState = new KeyWordRelName();
                keyWordRelState.setKeyWord(e.getKeyword());
                keyWordRelState.setName(all.get(e.getSwitchNodeId()));
                return keyWordRelState;
            }).collect(Collectors.toList());
            return keyWordRelStateList;
        } else {
            throw new BizException(LACK_KEY_WORD);
        }
    }

    private AIState initStateNodeData(AISOP aisop, StateNode stateNode) {
        AIState aiState = new AIState();
        aiState.setName(stateNode.getStateName());
        aiState.setBeginQuery(stateNode.getBeginQuery());
        aiState.setEnvironmentPrompt("");


        Integer maxNum = Optional.ofNullable(stateNode.getMaxHistory()).orElse(10);

        //agent 意图识别
        IntentRecognition agentConvertNew = new IntentRecognition();
        Map<String, String> allAgent = stateNode.getAgentNodes().stream().collect(Collectors.toMap(AgentNode::getNodeId, AgentNode::getAgentName,(key1 , key2)-> key1));
        if (judgeSameName(allAgent)){
            throw new BizException(AGENT_NOT_SAME_NAME);
        }
        settingSwitchData(stateNode.getAgentSwitchNode(), agentConvertNew, allAgent);
        // agent的意图识别
        aiState.setIntentRecognition(agentConvertNew);

        List<AIAgent> aiAgentList = new ArrayList<>();
        List<String> roleList = new ArrayList<>();
        //初始化agent
        if (ObjectUtil.isEmpty(stateNode.getAgentNodes())) {
            throw new BizException(NOT_LINK_AGENT);
        }
        for (AgentNode agentNode : stateNode.getAgentNodes()) {
            AIAgent aiAgent = initAgent(agentNode);
            aiAgentList.add(aiAgent);
            roleList.add(aiAgent.getRole());
        }
        // 如果是对话模式，默认添加用户Agent
        if (aisop.isDialogueMode()) {
            AIAgent aiAgent = initUserAgent(null);
            aiAgentList.add(aiAgent);
        }
        aiState.setAiAgentList(aiAgentList);
        return aiState;
    }

    private void settingSwitchData(SwitchNode stateSwitchNode, IntentRecognition intentRecognition, Map<String, String> all) {

        if (null == stateSwitchNode) {
            return;
        }
        if (stateSwitchNode.getSwitchType() == null) {
            throw new BizException(LACK_SWITCH_TYPE);
        }
        //默认为顺序
        intentRecognition.setType(stateSwitchNode.getSwitchType());
        intentRecognition.setHistoryMessage(stateSwitchNode.getUseHistory() == null ? false :stateSwitchNode.getUseHistory());
        Integer defaultIntentionType = stateSwitchNode.getDefaultIntentionType();
        //解析默认意图，默认场景
        if (defaultIntentionType == null || defaultIntentionType.equals(1)){
            List<SwitchDefaultAnswer> defaultAnswer = stateSwitchNode.getDefaultAnswer();
            if (CollectionUtil.isNotEmpty(defaultAnswer)) {
                List<String> answer = defaultAnswer.stream().map(e -> e.getAnswerValue()).collect(Collectors.toList());
                intentRecognition.setAnswerList(answer);
            }else {
                throw new BizException(LACK_DEFAULT_ANSWER);
            }
        }else if (defaultIntentionType.equals(2)){
            String defaultNode = stateSwitchNode.getDefaultNode();
            if (StringUtils.isEmpty(defaultNode)){
                throw new BizException(SWITCH_LACK_DEFAULT_INTENTION);
            }
            String name = all.get(defaultNode);
            intentRecognition.setAnswerList(Arrays.asList(name));
        }
        intentRecognition.setDefaultIntentType(stateSwitchNode.getDefaultIntentionType());
        if (null != stateSwitchNode) {
            //大模型切换
            if (ControllerTypeEnum.RULE.getValue().equals(stateSwitchNode.getSwitchType())) {
                if (ObjectUtil.isEmpty(stateSwitchNode.getRuleSwitchNodeList())) {
                    throw new BizException(ErrorCodeEnum.INTENTION_NOT_RULE);
                }
                for (RuleNode ruleNode : stateSwitchNode.getRuleSwitchNodeList()) {
                    if (ObjectUtil.isEmpty(ruleNode.getConditions())) {
                        List<RuleConditionBO> conditions = ruleNode.getConditions();
                        throw new BizException(INTENTION_NOT_RULE_CONDITION.getCode(), "意图识别节点规则【" + "" + "】未添加条件");
                    }
                }
                List<RuleNode> ruleSwitchNodeList = stateSwitchNode.getRuleSwitchNodeList();
                List<RuleConvert> ruleConvertList = ruleSwitchNodeList.stream().map(e -> {
                    if (null == e.getComponentId()){
                        throw new BizException(ErrorCodeEnum.LACK_COMP);
                    }
                    RuleConvert ruleConvert = new RuleConvert();
                    e.setSwitchNodeName(all.get(e.getSwitchNodeId()));
                    // 生成规则脚本
                    String ruleScript = GroovyScriptGeneratorUtil.generatorScript(1, e);
                    ruleConvert.setScript(ruleScript);
                    // 组件
                    APIComponent apiComponent = getApiComponent(e.getComponentId());
//                    apiComponent.setInParam(e.getInParam());
                    ruleConvert.setComponent(apiComponent);
                    // 组件入参映射
                    JSONArray jsonArray = JSON.parseArray(e.getInParam());
                    if (jsonArray != null && jsonArray.size() > 0) {
                        apiComponent.setInParam(e.getInParam());
                    }
                    if (StringUtils.isNotEmpty(apiComponent.getInParam())){
                        try {
                            log.info("-----------------------------{}",apiComponent.getInParam());
                            List<ComponentInParam> inParams = JSONObject.parseArray(apiComponent.getInParam(),ComponentInParam.class);
                            inParams.forEach(item->{
                                if(CollectionUtil.isEmpty(item.getTypeList())){
                                    throw new BizException(LACK_COMP_PARAM_SOURCE);
                                }
                            });
                        }catch (Exception exception){
                            List<ComponentInParamOld> oldList = JSONObject.parseArray(apiComponent.getInParam(),ComponentInParamOld.class);
                            throw new BizException(LACK_COMP_PARAM_SOURCE);
                        }

                    }

                    //脚本里面的参数对应关系
                    Map<String, String> ruleScriptMap = getRuleScriptParamMap(stateSwitchNode);
                    ruleConvert.setInParam(ruleScriptMap);
                    return ruleConvert;
                }).collect(Collectors.toList());
                intentRecognition.setRuleConvertList(ruleConvertList);
            } else {

                ComponentLLM componentLLM = null;
                if (null  == stateSwitchNode.getComponentId()){
                    componentLLM = getLLMComponent(138l);
                }else {
                    componentLLM = getLLMComponent(stateSwitchNode.getComponentId());
                    if (null == componentLLM) {
                        throw new BizException(LACK_BIG_MODEL);
                    }
                }
                intentRecognition.setLlm(componentLLM);
                List<KeyWordRelName> keyWordRelStateList = initKeyWordRelStateList(all, stateSwitchNode.getBigModelSwitchList());
                intentRecognition.setKeyWordRelNameList(keyWordRelStateList);
            }
        }
    }

    @NotNull
    private static Map<String, String> getRuleScriptParamMap(SwitchNode stateSwitchNode) {
        Map<String, String> ruleScriptMap = new HashMap<>();
        List<RuleNode> ruleNodeList = stateSwitchNode.getRuleSwitchNodeList();
        if (ObjectUtil.isNotEmpty(ruleNodeList)) {
            for (RuleNode ruleNode : ruleNodeList) {
                List<RuleConditionBO> conditions = ruleNode.getConditions();
                if (ObjectUtil.isNotEmpty(conditions)) {
                    for (RuleConditionBO condition : conditions) {
                        String outParams = condition.getOutParams();
                        String[] splitList = outParams.split(",");
                        ruleScriptMap.put(splitList[0], splitList[0]);
                    }
                }
            }
        }

        return ruleScriptMap;
    }


    private ComponentLLM getLLMComponent(Long compId) {
        if (compId != null) {
            Component component = componentGateway.findById(compId);
            if (null != component) {
                Interface interfaces = interfaceGateway.get(component.getInterfaceId());
                ComponentLLM llm = new ComponentLLM();
                if (interfaces == null) {
                    String interfaceList = component.getInterfaceList();
                    JSONArray jsonArray = JSON.parseArray(interfaceList);
                    interfaces = interfaceGateway.get(jsonArray.getLong(0));
                }
                if (interfaces != null) {
                    llm.setUrl(interfaces.getHostUrl() + interfaces.getUrl());
                    llm.setRequestMethod(interfaces.getRequestMethod());
                    llm.setInParam(interfaces.getInParam());
                    llm.setModel(interfaces.getInterfaceName());
                    llm.setType(component.getType());
                }
                return llm;
            }
        }
        return null;
    }

    private APIComponent getApiComponent(Long compId) {
        List<ComponentVO> componentDOList = this.componentGateway.listByIdList(Arrays.asList(compId));
        if (ObjectUtil.isEmpty(componentDOList)) {
            throw new BizException(COMPONENT_NOT_EXIST.getCode(), "组件【" + compId + "】不存在");
        }
        return initComponent(componentDOList.get(0));
    }

    *//**
     * @param agentNode
     * @return
     *//*
    private AIAgent initAgent(AgentNode agentNode) {
        AIAgent aiAgent = new AIAgent();
        aiAgent.setName(agentNode.getAgentName());
        aiAgent.setExecComList(new ArrayList<>());

        if (agentNode.getBigCompId() == null && CollectionUtil.isEmpty(agentNode.getComponentNodes())) {
            throw new BizException(AGENT_LACK_COMP);
        }

        if (agentNode.getBigCompId() != null) {
            ComponentLLM bigModel = getLLMComponent(agentNode.getBigCompId());
            if (null != bigModel) {
                aiAgent.setComLLM(bigModel);
            }
        }

        //指令
        aiAgent.setPrompt(agentNode.getInstruct());
        // 配置组件关联关系
        aiAgent.setApiComponentList(obtainCommonComponent(agentNode));
        // 配置agent出参
        aiAgent.setResponse(agentNode.getOutParamContent());
        //解析出参的用到的组件参数
        List<ComponentParam> componentParamList = new ArrayList<>();
        analyzeAgentResponse(agentNode.getOutParamContent(), componentParamList);
        aiAgent.setComponentParamList(componentParamList);
        return aiAgent;
    }

    private List<APIComponent> obtainCommonComponent(AgentNode agentNode) {

        List<APIComponent> apiComponentList = new ArrayList<>();

        List<ComponentNode> componentNodes = agentNode.getComponentNodes();

        if (CollectionUtil.isEmpty(componentNodes)) {
            return apiComponentList;
        }
        //关联组件
        List<Long> comIds = componentNodes.stream().map(e -> e.getCompId()).collect(Collectors.toList());
        //查询组件
        List<ComponentVO> componentList = listComponentByAgentId(comIds,componentNodes);
        Map<Long,ComponentVO> componentNodeMap = componentList.stream().collect(Collectors.toMap(ComponentVO::getCompId,Function.identity(),(key1 , key2)-> key1));
        if (CollUtil.isNotEmpty(componentList)) {
            for (ComponentNode componentNode : componentNodes) {
                ComponentVO componentVO = componentNodeMap.get(componentNode.getCompId());
                APIComponent apiComponent = initComponent(componentVO);
                log.info("-----------{}",componentVO.getCompType());
                if (!componentVO.getCompType().equals(1) && StringUtils.isNotEmpty(componentNode.getInParam()) ){
                    try {
                        List<ComponentInParam> inParams = JSONObject.parseArray(componentNode.getInParam(),ComponentInParam.class);
                        inParams.forEach(item->{
                            if(CollectionUtil.isEmpty(item.getTypeList())){
                                throw new BizException(LACK_COMP_PARAM_SOURCE.getCode(),"组件 ["+ componentNode.getCompName()+"] 入参来源必填");
                            }
                        });
                    }catch (Exception exception){
                        throw new BizException(LACK_COMP_PARAM_SOURCE.getCode(),"组件 ["+ componentNode.getCompName()+"] 入参来源必填");
                    }
                    apiComponent.setInParam(componentNode.getInParam());
                }
                // 出参，入参，存储历史会话，是否重新生成结果， 用节点的数据
                apiComponent.setRepeat(componentNode.getRepeat() == null ? false : componentNode.getRepeat().equals(1) ? true :false);
                apiComponentList.add(apiComponent);
            }
        }
        return apiComponentList;
    }


    private APIComponent initComponent(ComponentVO component) {

        APIComponent apiComponent = new APIComponent();
        BeanUtils.copyProperties(component, apiComponent);
        apiComponent.setAdapterParam(component.getAdapterInParam());
        apiComponent.setName(component.getCompName());
        apiComponent.setDescription(component.getDescription());
        apiComponent.setCode(component.getCompCode());
        apiComponent.setId(component.getCompId());
        apiComponent.setInParam(component.getInParam());
        apiComponent.setOutParam(component.getOutParam());
        apiComponent.setRepeat(component.isRepeat());
        apiComponent.setType(component.getType());
        apiComponent.setConfigureType(component.getConfigureType());
        //组件类型是大模型
        if (component.getCompType() == 1) {

            AgentComponentLLM componentLLM = new AgentComponentLLM();
            ComponentLLM bigModel = getLLMComponent(apiComponent.getId());
            componentLLM.setComponentLLM(bigModel);
            if (component.getTemperature() != null){
                componentLLM.setTemperature(component.getTemperature()/100);
            }
            if (ObjectUtil.isNotEmpty(component.getPromptRule())) {
                List<String> userParam = new ArrayList<>();
                List<String> systemParam = new ArrayList<>();
                Map<Long, List<String>> compParam = new HashMap<>();
                analyzePrompt(component.getPromptRule(), userParam, systemParam, compParam);
                componentLLM.setSystemParam(userParam);
                componentLLM.setCustomerParam(systemParam);
                componentLLM.setComponentParam(compParam);
            }else {
                throw new BizException(LACK_PROMPT.getCode(),LACK_PROMPT.getMsg().replace("*",component.getCompName()));
            }
            componentLLM.setPrompt(component.getPromptRule());

            apiComponent.setComponentLLM(componentLLM);
        }

        String interfaceStr = component.getInterfaceList();
        if (ObjectUtil.isNotEmpty(interfaceStr)) {
            List<Interface> apiList = interfaceGateway.listByIdList(JSONObject.parseArray(interfaceStr, Long.class));
            List<InterfaceBO> interfaceBOList = new ArrayList<>();
            for (Interface api : apiList) {
                InterfaceBO interfaceBO = new InterfaceBO();
                interfaceBO.setInterfaceId(api.getId());
                interfaceBO.setUrl(api.getHostUrl() + api.getUrl());
                interfaceBO.setRequestMethod(api.getRequestMethod());
                interfaceBO.setInParam(api.getInParam());
                interfaceBOList.add(interfaceBO);
            }
            apiComponent.setInterfaceBOList(interfaceBOList);
        }
        try {
            if (ObjectUtil.isNotEmpty(component.getInterfaceDependency())) {
                LogicFlow logicFlow = JSONObject.parseObject(component.getInterfaceDependency(), LogicFlow.class);
                ELParser elParser = new LogicFlowParser(logicFlow);
                ELNode elNode = elParser.extractElNode();
                String elExpress = createChain(logicFlow, elNode.generateEl());
                apiComponent.setElExpress(elExpress);
            }
        } catch (ExpressLanguageParseException e) {
            log.error("组件API转换执行流程出错", e);
            throw new BizException(COMPONENT_API_CONVERT_ERROR);
        }
        return apiComponent;
    }

    public List<ComponentVO> listComponentByAgentId(List<Long> compIds, List<ComponentNode> componentDTOList) {
        List<ComponentVO> componentDOList = this.componentGateway.listByIdList(compIds);

        // 将组件之间出入参适配返回
        if (CollUtil.isNotEmpty(componentDOList)) {
            // agent关联组件
            Map<Long, ComponentNode> agentComponentMap = componentDTOList.stream().collect(Collectors.toMap(ComponentNode::getCompId, Function.identity(), (a, b) -> a));
            //封装组件参数
            for (ComponentVO componentVO : componentDOList) {
                ComponentNode componentNode = agentComponentMap.get(componentVO.getCompId());
                if (componentNode != null) {
                    componentVO.setAdapterInParam(componentNode.getAdapterInParam());
                    componentVO.setOutParamType(componentNode.getOutParamType());
                    componentVO.setStoreMemory(componentNode.getStoreMemory());
                    componentVO.setRepeat(componentNode.getRepeat() == null || componentNode.getRepeat() == 0 ? false : true);
                    componentVO.setInParam(componentNode.getInParam());
                    componentVO.setOutParam(componentNode.getOutParam());
                    componentVO.setTemperature(componentNode.getTemperature());
                    componentVO.setPromptRule(componentNode.getPromptRule());
                }
            }
        }
        return componentDOList;
    }

    public AIAgent initUserAgent(String userName) {
        AIAgent aiAgent = new AIAgent();
        aiAgent.setName(Optional.ofNullable(userName).orElse("User"));
        aiAgent.setStyle("");
        aiAgent.setRole("User");
        aiAgent.setUser(true);
        return aiAgent;
    }

    private static String createChain(LogicFlow logicFlow, String oldElExpress) {
        String elExpress = oldElExpress;
        List<LfNode> nodeList = logicFlow.getNodes().stream()
                .filter(e -> !e.getType().equals("StartNode") && !e.getType().equals("EndNode"))
                .collect(Collectors.toList());

        for (LfNode lfNode : nodeList) {
            NodeProperties properties = lfNode.getProperties();
            String type = properties.getNodeType();
            if (type == null) {
                continue;
            }
            Long apiId = properties.getApiId();

            String nodeId = properties.getNodeId();

            if (nodeId == null) {
                continue;
            }
            elExpress = elExpress.replace(nodeId, "liteFlowNode.tag(\"" + apiId + "\")");

        }
        return elExpress;
    }


    private static void analyzeAgentResponse(String response, List<ComponentParam> componentParams) {
        if (StringUtils.isEmpty(response)) {
            return;
        }
        int l = 0;
        char[] chars = response.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            char c = chars[i];
            if (chars[i] == '{') {
                l = i;
            } else if (chars[i] == '}') {
                String str = response.substring(l, i);
                if (StringUtils.isNotEmpty(str)) {
                    String[] strings = str.split("-");
                    Long id = Long.valueOf(strings[1]);
                    String code = strings[2];
                    ComponentParam componentParam = new ComponentParam();
                    componentParam.setComponentId(Long.valueOf(id));
                    componentParam.setParamCode(code);
                    componentParams.add(componentParam);
                }

            }
        }
    }

    private void getDefaultBigComp() {
        if ("dev".equals(profile) || "local".equals(profile)) {

        } else if ("itest".equals(profile)) {

        }

    }

    private void analyzePrompt(String prompt, List<String> userParam, List<String> systemParam, Map<Long, List<String>> compParam) {
        if (ObjectUtil.isEmpty(prompt)) {
            return;
        }
        int l = 0;
        int r = 0;
        char[] chars = prompt.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == '{') {
                l = i;
            } else if (chars[i] == '}') {
                r = i;
                String str = prompt.substring(l + 1, r);
                if (str.startsWith("custom")) {
                    userParam.add(str);
                } else if (str.startsWith("sys")) {
                    systemParam.add(str);
                } else if (str.startsWith("comp")) {
                    String[] strings = str.split("-");
                    Long id = Long.valueOf(strings[1]);
                    String code = strings[2];
                    if (compParam.containsKey(id)) {
//                        List<String> codes = compParam.get(id);
//                        codes.add(code);
//                        compParam.put(id,codes);
                        compParam.get(id).add(code);
                    } else {
                        List<String> codes = new ArrayList<>();
                        codes.add(code);
                        compParam.put(id,  codes);
                    }
                }
            }
        }
    }
*/
}
